<template>
  <div class="app-container bg-white">
    <!-- 页面头部 -->
    <div class="page-header flex align-center space-between">
      <div class="font-weight--lg font-size--lg">{{title}}商品属性</div>
    </div>

    <div class="page-body" v-loading="pageLoading">
      <el-form :model="myForm" ref="myFormRef" label-width="100px" :label-position="'top'" class="form_box">
        <el-row :gutter="40">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="属性名称" required>
                  <el-input v-model="myForm.name" placeholder="请输入属性名称" @input="watchInput($event, 'name')" maxlength="10" show-word-limit></el-input>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <!-- required -->
                <el-form-item label="属性编码" required class="margin_bottom_none"> 
                  <el-input v-model="myForm.number" placeholder="请输入属性编码" maxlength="3" @keydown.native="inputUnpass" @input="inputSuppCode1" show-word-limit disabled></el-input>
                  <span class="text-gray">(请输入数字或大写字母)</span>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="排序" required>
                  <el-input v-model="myForm.sort" placeholder="请输入4位之内纯数字" class="full-width text-left" maxlength="4" show-word-limit @keydown.native="inputNoneNumberUnpass" @input="inputCodeNumber"></el-input>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-form-item label="属性描述">
                  <el-input type="textarea" v-model="myForm.subtitle" placeholder="请输入属性描述" maxlength="500" show-word-limit></el-input>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <!-- <el-form-item label="属性已绑定分类">
                <el-table :data="tableData" border max-height="480" @selection-change="handleSelectionChange">
                  <el-table-column type="selection" width="42"></el-table-column>
                  <el-table-column type="index" label="序号" width="80"></el-table-column>
                  <el-table-column prop="name" label="绑定分类">
                    <template slot-scope="scope">
                      <div v-if="scope.row.hasSelect">
                        <el-cascader size="small" placeholder="请选择商品分类" v-model="scope.row.classIds" clearable :options="storeClassList" :props="defaultProps"></el-cascader>
                      </div>
                      <div v-else>{{scope.row.name}}</div>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作">
                    <template slot-scope="scope">
                      <template v-if="itemId">
                        <el-button size="mini" @click="oneBind(scope.row)" v-if="scope.row.hasSelect">保存</el-button>
                        <el-button size="mini" type="danger" @click="oneUnBind(scope.row.id, scope.$index)" v-else>解绑</el-button>
                      </template>
                      <template v-else>
                        <el-button size="mini" type="danger" @click="deleteBind(scope.$index)">删除</el-button>
                      </template>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="margin_top_20">
                  <el-button @click="addClassOption()" v-if="roleBtns.includes('sys:properties:bind') || $store.getters.isAdmin">新增分类</el-button>
                  <el-button type="danger" @click="allUnBind()" v-if="itemId && (roleBtns.includes('sys:properties:unbind') || $store.getters.isAdmin)">全部解绑</el-button>
                </div>
              </el-form-item> -->
              
              <el-form-item label="属性值" required>
                <el-table :data="tagList" border max-height="480">
                  <el-table-column type="index" label="序号" width="80"></el-table-column>
                  <el-table-column prop="valueName" label="属性值">
                    <template slot-scope="scope">
                      <el-tooltip class="item" effect="light" :content="scope.row.valueName" placement="top" v-if="scope.row.valueName.length>20">
                        <el-input v-model.trim="scope.row.valueName" placeholder="请输入属性值" maxlength="100" show-word-limit></el-input>
                      </el-tooltip>
                      <el-input v-else v-model.trim="scope.row.valueName" placeholder="请输入属性值" maxlength="100" show-word-limit></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="valueNo" label="属性值编码(请输入数字或大写字母)">
                    <template slot-scope="scope">
                      <el-input v-model.trim="scope.row.valueNo" placeholder="请输入属性值编码" :title="scope.row.valueNo" disabled @keydown.native="inputUnpass" @input="inputSuppCode(scope)" show-word-limit></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作">
                    <template slot-scope="scope">
                      <!-- <el-button size="mini" v-if="!scope.row.isEdit" @click="scope.row.isEdit = true">编辑</el-button>
                      <el-button size="mini" v-if="scope.row.isEdit" @click="saveValueItemOption(scope.row)">保存</el-button> -->
                      <el-button size="mini" type="danger" @click="removeAttrItem(scope.row, scope.$index)" v-if="!scope.row.id || (roleBtns.includes('sys:properties:remove_values') || $store.getters.isAdmin)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="margin_top_20">
                  <el-button @click="addValueItemOption()">添加属性值</el-button>
                </div>
              </el-form-item>
            </el-col>
        </el-row>
        <el-button type="primary" @click="submitOption()" :loading="submitLoading">保存</el-button>
        <el-button @click="goBack()">取消</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
import Setting from '@/settings';
import { mapGetters } from 'vuex';
import { GetStoreAttrItemDetail, GetStoreAttrItemBindClass, DeleteStoreAttrItemValueOne,
 AddStoreAttrItemValueOne, UpdateStoreAttrItemValueOne, BindCategory, UnBindCategory, GetStoreClassList } from '@/views/store-management/services/index';

export default {
  data() {
    return {
      itemId: null,
      myForm: {
        name: '',
        number: '',
        sort: 0,
        subtitle: ''
      },
      tagList: [],
      tableData: [],
      storeClassList: [],
      multipleSelection: [],
      deleteTagIds: [],
      submitLoading: false,
      pageLoading: false,
      defaultProps: {
        value: 'id',
        label: 'title',
        children: 'goodsCategoryModelList'
      }
    }
  },
  computed: {
    title() {
      return this.itemId ? '编辑' : '新增';
    },
    ...mapGetters(['roleBtns'])
  },
  created() {
    this.getStoreClassList();
    if (this.$route.query.id) {

      this.itemId = this.$route.query.id;
      this.pageLoading = true;
      GetStoreAttrItemDetail({id: this.$route.query.id})
      .finally(() => this.pageLoading = false)
      .then(data => {
        if (data.code == 200) {
          this.myForm.name = data.data.propertyName;
          this.myForm.number = data.data.propertyNo;
          this.myForm.sort = data.data.sort;
          this.myForm.subtitle = data.data.subtitle;
          this.tagList = data.data.propertyValuesList.map(item => {
            return {
              id: item.id,
              isEdit: false,
              valueName: item.valueName,
              valueNo: item.valueNo
            }
          });
        } else {
          this.$message.error('商品属性信息获取失败!');
          return;
        }
      })

      this.getBindClassList();
    }
  },
  methods: {
    inputSuppCode(scope) {
           scope.row.valueNo=scope.row.valueNo.replace(/[^\w\.\/]/ig,'').toUpperCase();
     },
     inputSuppCode1(val) {
           val=val.replace(/[^\w\.\/]/ig,'');
           this.myForm.number = val.toUpperCase();
     },
    //  限制名称不能输入特殊字符
    watchInput(event, key) {
      this.myForm[key] = this.inputReplaceSpecialChar(event)
    },
     //限制排序只能输入整数
     inputCodeNumber(val) {
          val=val.replace(/\D/g,'');
          this.myForm.sort = val;
       },
    addClassOption() {
      this.tableData.push({
        id: '',
        name: '',
        title: '',
        classIds: [],
        hasSelect: true
      })
    },
    oneBind(rowData) {
      if (!rowData.classIds || !rowData.classIds.length) {
        this.$message.warning('请选择需要绑定的商品分类!');
        return;
      }
      this.pageLoading = true;
      BindCategory({
        propertyId: this.itemId, // 属性id	
        propertyName: this.myForm.name, // 属性名	
        categoryId: rowData.classIds[rowData.classIds.length - 1]
      })
      .finally(() => this.pageLoading = false)
      .then(data => {
        if (data.code == 200) {
          this.$message.success('绑定成功!');
          this.getBindClassList();
        } else {
          this.$message.error('绑定失败!');
        }
      })
    },
    allUnBind() {
      this.$confirm('此操作将全部解除该属性绑定的分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            UnBindCategory({ propertyId: this.itemId })
            .then(data => {
              instance.confirmButtonLoading = false;
              if (data.code == 200) {
                done();
                this.$message.success('解绑成功!');
                this.tableData = [];
              } else {
                this.$message.error('解绑失败!');
              }
            })
            .catch(error => {
              instance.confirmButtonLoading = false;
            })
          } else {
            done();
          }
        }
      })
    },
    oneUnBind(rowId, index) {
      this.$confirm('此操作将全部解除该属性绑定的分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            UnBindCategory({ propertyId: this.itemId, categoryId: rowId })
            .then(data => {
              instance.confirmButtonLoading = false;
              if (data.code == 200) {
                done();
                this.$message.success('解绑成功!');
                this.tableData.splice(index, 1);
              } else {
                this.$message.error('解绑失败!');
              }
            })
            .catch(error => {
              instance.confirmButtonLoading = false;
            })
          } else {
            done();
          }
        }
      })
    },
    deleteBind(index) {
      this.tableData.splice(index, 1);
    },
    handleSelectionChange(selectlist) {
      this.multipleSelection = selectlist;
    },
    // 新增单项属性值
    addValueItemOption() {
      this.tagList.unshift({
        id: '',
        // isEdit: true,
        valueName: '',
        valueNo: ''
      })
    },
    saveValueItemOption(rowData) {
      if (!rowData.valueName) {
        this.$message.warning('请输入属性值!');
        return;
      }
      if (!(Setting.expression[0].value).test(rowData.valueNo)) {
        this.$message.warning('属性值编码只能输入字母和数字!');
        return;
      }
      const isInclude = this.tagList.filter(item => item.valueName == rowData.valueName || item.valueNo == rowData.valueNo);
      if (isInclude && isInclude.length && isInclude.length == 2) {
        this.$message.warning('请勿输入重复属性值');
        return;
      }
      rowData.isEdit = false;
    },
  
    // 删除标签删除属性值
    removeAttrItem(tag, index) {
      if (!tag.id) {
        this.tagList.splice(index, 1);
        return;
      } else {
        this.deleteTagIds.push(tag.id);
        this.tagList.splice(index, 1);
        return;
      }
    },
    // 保存按钮完成
    submitOption() {
      if (!this.myForm.name) {
        this.$message.warning('请输入属性名称!');
        return;
      }
      // if (!this.myForm.number) {
      //   this.$message.warning('请输入属性编码!');
      //   return;
      // }
      // if (this.myForm.number.length < 3) {
      //   this.$message.warning('属性编码长度不足3位!');
      //   return;
      // }
      // if (!(Setting.expression[0].value).test(this.myForm.number)) {
      //   this.$message.warning('属性编码只能输入字母和数字!');
      //   return;
      // }
      if (!this.myForm.sort) {
        this.$message.warning('请输入排序!');
        return;
      }
      if (!this.tagList || !this.tagList.length) {
        this.$message.warning('请至少填写一项属性值!');
        return;
      }

      const isAllName = this.tagList.every(item => item.valueName);
      if (!isAllName) {
        this.$message.warning('请输入属性值!');
        return;
      }

      // const isAllCode = this.tagList.every(item => item.valueNo);
      // if (!isAllCode) {
      //   this.$message.warning('请输入属性值编码!');
      //   return;
      // }

      // const isAllLength = this.tagList.every(item => item.valueNo.length == 3);
      // if (!isAllLength) {
      //   this.$message.warning('属性值编码不足3位!');
      //   return;
      // }

      // const isAllValid = this.tagList.every(item => (Setting.expression[0].value).test(item.valueNo));
      // if (!isAllValid) {
      //   this.$message.warning('属性值编码只能输入字母和数字!');
      //   return;
      // }

      const nameObj = {};
      let isInclude = false;
      for(let i = 0; i < this.tagList.length; i++) {
        if (nameObj[this.tagList[i].valueName]) {
          nameObj[this.tagList[i].valueName] += 1;
          isInclude = true;
          break;
        } else {
          nameObj[this.tagList[i].valueName] = 1;
        }
      }

      if (isInclude) {
        this.$message.warning('请勿输入重复属性值');
        return;
      }
      this.submitLoading = true;
      // 异步执行删除
      if (this.deleteTagIds && this.deleteTagIds.length) {
        DeleteStoreAttrItemValueOne({ targetIds: this.deleteTagIds.map(item => item).join(',') })
        .then(data => {
          instance.confirmButtonLoading = false;
          if (data.code == 200) {
            this.$message.success('删除成功!');
          }
        })
      }
      let queryParams = {
        propertyName: this.myForm.name,
        propertyNo: this.myForm.number.toUpperCase(),
        sort: this.myForm.sort,
        subtitle: this.myForm.subtitle,
        propertyValuesList: this.tagList.map(item => {
          delete item.isEdit;
          return item;
        }),
        // 随便写的
        // categoryId: 1,
        creatorId: JSON.parse(this.$store.getters.userInfo).id ? JSON.parse(this.$store.getters.userInfo).id : '1',
      };
      // 判断一下是否是编辑还是新增
      if (this.itemId) {
        queryParams['id'] = this.itemId;
        // 进入这个是属于编辑按钮
        UpdateStoreAttrItemValueOne(queryParams)
        .then(data => {
          this.submitLoading = false;
          if (data.code == 200) {
            this.$message.success('修改成功!');
            this.goBack();
          } else {
            this.$message.error('修改失败!');
          }
        })
        .catch(error => {
          this.submitLoading = false;
        })
      } else {
        // 进入这个是属于新增数据
        AddStoreAttrItemValueOne({
          ...queryParams,
          categoryList: this.tableData.map(item => {
            return {id: item.classIds[item.classIds.length - 1]}
          })
        })
        .then(data => {
          this.submitLoading = false;
          if (data.code == 200) {
            this.$message.success('保存成功!');
            this.goBack();
          } else {
            this.$message.error('保存失败!');
          }
        })
        .catch(error => {
          this.submitLoading = false;
        })
      }
    },
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },
    getBindClassList() {
      GetStoreAttrItemBindClass({ propertyId: this.itemId })
      .then(data => {
        if (data.code == 200 && data.data.length) {
          this.tableData = data.data.map(item => {
            return {
              id: item.id,
              name: item.relationRule,
              title: item.title,
              classIds: [],
              hasSelect: false
            }
          });
        }
      })
    },
    getStoreClassList() {
      GetStoreClassList()
      .then(data => {
        this.storeClassList = data.data;
      })
    },
    updated() {
    this.$nextTick(() => {
      const numberInputList = document.querySelectorAll('.el-input-number input.el-input__inner');
      numberInputList.forEach(item => {
        item.type = 'number';
      })
    })
  }
  }
}
</script>

<style lang="scss" scoped>
.form_box {
    max-width: 1064px;
    padding: 0 100px;
    box-sizing: content-box;
}

::v-deep .el-input-number .el-input__inner {
  text-align: left;
  line-height: 1px!important;
  overflow:hidden; //必须
  white-space:nowrap; //必须
  text-overflow:ellipsis; //必须
}
</style>
